/**
 * Created on Mar 15, 2007
 *
 * A string pool. This can be used to save memory.
 *
 * This is different from using String.intern() because those
 * Strings might not be garbage collected.
 *
 * @author Christopher Brady
 */
package org.ddevil.data;

import java.io.Serializable;
import java.util.HashMap;


public class StringPool implements Serializable {

	// The pool of Strings
	protected HashMap<String, String> pool;

	/**
	 * maxStrings is the max number of strings that will be added.
	 * Setting maxStrings too low will hurt performance and setting
	 * it too high will waste memory.
	 */
	public StringPool(int maxStrings) {
		int initialCapacity = (int)(maxStrings/.75);
		pool = new HashMap<String, String>(initialCapacity, (float).75);
	}

	/**
	 * Returns string a from the pool if it exists.
	 * If it does not exist, a will be added to the pool and then
	 * returned.
	 */
	public String getString(String a) {
		String returnString;

		if( a != null ) {
			if(pool.containsKey(a)) {
				returnString = pool.get(a);
			} else {
				pool.put(a, a);
				returnString = a;
			}
		} else {
			returnString = null;
		}

		return returnString;
	}

	/**
	 * Returns the number of Strings in the pool.
	 */
	public int size() {
		return pool.size();
	}
}
